// order-submit.js
var api = require('../../config/api.js');
var util = require('../../utils/util.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl:api.RootUrl,
    freightPrice: 0.00,
    couponPrice: 0.00,
    booksTotalPrice:0.00,
    orderTotalPrice: 0.00,
    actualPrice: 0.00,
    content: '',

    offline: 0,
    
    name:"",
    phone:"",
    address: null,
    couponId:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var page = this;
    
  },

  //备注
  bindkeyinput: function (e) { 
    this.setData({
      content: e.detail.value
    });
  },
  KeyName: function (e) {
    this.setData({
      name: e.detail.value
    });
  },
  KeyPhone: function (e) {
    this.setData({
      phone: e.detail.value
    });
  },
  /**
   *  切换是门店自提还是线上 
   */
  getOffline: function (e) {
    var freightPrice = this.data.freightPrice;
    var freightPrice_1 = this.data.freightPrice_1;
    var offline = e.target.dataset.index;
    if (offline == 1) {
      this.setData({
        offline: offline,
        freightPrice:0,
        freightPrice_1: freightPrice
      });
    } else {
      this.setData({
        offline: offline,
        freightPrice: freightPrice_1
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var page = this;
    var address = wx.getStorageSync("picker_address");
    if (address) {
      page.setData({
        address: address,
        name:address.receivername,
        phone:address.mobile
      });
      wx.removeStorageSync("picker_address");
    }
    var couponId = wx.getStorageSync('couponId');
    if (couponId) {
      page.setData({
        'couponId': couponId
      });
    }
    page.getOrderData(page.options);
  },

  //获取数据
  getOrderData: function (options) {
    var page = this;
    var address_id = "";
    if (page.data.address && page.data.address.id)
      address_id = page.data.address.id;
    //购物车中的商品
    if (options.cartIdList) {
      var cartIdList = JSON.parse(options.cartIdList);
      wx.showLoading({
        title: "正在加载",
        mask: true,
      });//cartIdList: options.cartIdList,参数
      page.data.cartIdList = cartIdList;
      util.request(api.CartCheckout, {addressId: address_id}).then(function(res){
        wx.hideLoading();
        if (res.errno == 0) {
          page.setData({
            booksTotalPrice: parseFloat(res.data.booksTotalPrice),//商品总
            orderTotalPrice: parseFloat(res.data.orderTotalPrice),//订单总
            actualPrice: parseFloat(res.data.actualPrice),//实际总
            freightPrice: parseFloat(res.data.freightPrice),//邮费
            cartList: res.data.checkedBooksList,
            //cartList: res.data.cartList,
            address: res.data.address,
            couponList: res.data.couponList,
            //shop_list: res.data.shop_list,
            //shop: res.data.shop_list[0]||{},
            name: res.data.address.receivername,
            phone: res.data.address.phone
          });
          for (var i = 0; i < page.data.couponList.length;i++){
            page.data.couponList[i].useStartTime = util.formatTime(page.data.couponList[i].useStartTime);
            page.data.couponList[i].useEndTime = util.formatTime(page.data.couponList[i].useStartTime);
          }
          console.log(page.data.couponList);
        }
      })
    }
    //有可能是直接购买的，不是放在购物车的情况
    if (options.bookInfo) {
      wx.showLoading({
        title: "正在加载",
        mask: true,
      });
      util.request(api.BookCheckOut, { bookInfo: options.bookInfo},'post').then(function(res){
        wx.hideLoading();
        if (res.errno == 0) {
          page.setData({
            booksTotalPrice: parseFloat(res.data.booksTotalPrice),//商品总
            orderTotalPrice: parseFloat(res.data.orderTotalPrice),//订单总
            actualPrice: parseFloat(res.data.actualPrice),//实际总
            freightPrice: parseFloat(res.data.freightPrice),//邮费
            //cartList: res.data.checkedBooksList,
            bookInfo: res.data.bookInfo,
            address: res.data.address,
            couponList: res.data.couponList,
            name: res.data.address.receivername,
            phone: res.data.address.phone,
            num:res.data.num
          });
          for(var i = 0 ;i<page.data.couponList.length;i++){
            page.data.couponList[i].useStartTime = util.formatTime(page.data.couponList[i].useStartTime);
            page.data.couponList[i].useEndTime = util.formatTime(page.data.couponList[i].useEndTime);
          }
        }
        if (res.errno == 1) {
          wx.showModal({
            title: "提示",
            content: res.msg,
            showCancel: false,
            confirmText: "返回",
            success: function (res) {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1,
                });
              }
            }
          });
        }
      })

    }
  },

  //提交到订单
  orderSubmit: function () {
    var page = this;
    var offline = page.data.offline;
    var data = {};
    if (offline == 0) {//线上
      if (!page.data.address || !page.data.address.id) {
        wx.showToast({
          title: "请选择收货地址",
          image: "/images/icon-warning.png",
        });
        return;
      }
      data.addressId = page.data.address.id;
      data.address = page.data.address;
    } else {//线下
      data.address_name = page.data.name;
      data.address_phone = page.data.phone;
      data.shop_id = page.data.shop.id;
    }
    data.offline = offline;
    if (page.data.cartList) {
      data.cartList = JSON.stringify(page.data.cartList);
    }
    if (page.data.cartIdList) {
      data.cartIdList = JSON.stringify(page.data.cartIdList);
    }
    if (page.data.bookInfo) {//从订单详情 直接购买
      data.bookInfo = JSON.stringify(page.data.bookInfo);
    }
    if (page.data.picker_coupon) {//选到的优惠券
      data.couponId = page.data.picker_coupon.id;
      data.coupon = page.data.picker_coupon;
    }
    if (page.data.content) {
      data.content = page.data.content
    }
    if (page.data.freightPrice) {
      data.freightPrice = page.data.freightPrice
    }
    wx.showLoading({
      title: "正在提交",
      mask: true,
    });
    //提交订单,请求
    util.request(api.OrderSubmit,{data:data},"post").then(function(res){
      if (res.errno == 0) {
        setTimeout(function () {
          wx.hideLoading();
        }, 1000);
        setTimeout(function () {
          page.setData({
            options: {},
          });
        }, 1);
        var orderId = res.data.orderId;
        //获取支付数据,获取微信统一下单prepay_id 此功能因为是个人的，所以没办法使用支付功能
        util.request(api.OrderPay, { orderId: orderId, pay_type: 'WECHAT_PAY' }).then(function (res) {
            if (res.errno == 0) {
              //发起支付
              wx.requestPayment({
                timeStamp: res.data.timeStamp,
                nonceStr: res.data.nonceStr,
                package: res.data.package,
                signType: res.data.signType,
                paySign: res.data.paySign,
                success: function (e) {
                  wx.redirectTo({
                    url: "/pages/order/order?status=2",
                  });
                },
                fail: function (e) {
                  console.log("fail");
                  console.log(e);
                },
                complete: function (e) {
                  if (e.errMsg == "requestPayment:fail" || e.errMsg == "requestPayment:fail cancel") {//支付失败转到待支付订单列表
                    wx.showModal({
                      title: "提示",
                      content: "订单尚未支付",
                      showCancel: false,
                      confirmText: "确认",
                      success: function (res) {
                        if (res.confirm) {
                          wx.redirectTo({
                            url: "/pages/order/order?status=1",
                          });
                        }
                      }
                    });
                    return;
                  }
                  if (e.errMsg == "requestPayment:ok") {
                    return;
                  }
                  wx.redirectTo({
                    url: "/pages/order/order?status=-1",
                  });
                },
              });
              return;
            }
            if (res.errno == 1) {
              wx.showToast({
                title: res.errmsg,
                image: "/images/icon-warning.png",
                duration:3000,
              });
              return;
            }
          
        });
      }
      if (res.errno == 1) {
        wx.hideLoading();
        wx.showToast({
          title: res.errmsg,
          image: "/images/icon-warning.png",
        });
        return;
      }
    });

    /*app.request({
      url: api.order.submit,
      method: "post",
      data: data,
      success: function (res) {
        if (res.code == 0) {
          setTimeout(function () {
            wx.hideLoading();
          }, 1000);
          setTimeout(function () {
            page.setData({
              options: {},
            });
          }, 1);
          var orderId = res.data.orderId;

          //获取支付数据
          app.request({
            url: api.order.pay_data,
            data: {
              orderId: orderId,
              pay_type: 'WECHAT_PAY',
            },
            success: function (res) {
              if (res.code == 0) {
                //发起支付
                wx.requestPayment({
                  timeStamp: res.data.timeStamp,
                  nonceStr: res.data.nonceStr,
                  package: res.data.package,
                  signType: res.data.signType,
                  paySign: res.data.paySign,
                  success: function (e) {
                    wx.redirectTo({
                      url: "/pages/order/order?status=1",
                    });
                  },
                  fail: function (e) {
                  },
                  complete: function (e) {
                    if (e.errMsg == "requestPayment:fail" || e.errMsg == "requestPayment:fail cancel") {//支付失败转到待支付订单列表
                      wx.showModal({
                        title: "提示",
                        content: "订单尚未支付",
                        showCancel: false,
                        confirmText: "确认",
                        success: function (res) {
                          if (res.confirm) {
                            wx.redirectTo({
                              url: "/pages/order/order?status=0",
                            });
                          }
                        }
                      });
                      return;
                    }
                    if (e.errMsg == "requestPayment:ok") {
                      return;
                    }
                    wx.redirectTo({
                      url: "/pages/order/order?status=-1",
                    });
                  },
                });
                return;
              }
              if (res.code == 1) {
                wx.showToast({
                  title: res.msg,
                  image: "/images/icon-warning.png",
                });
                return;
              }
            }
          });
        }
        if (res.code == 1) {
          wx.hideLoading();
          wx.showToast({
            title: res.msg,
            image: "/images/icon-warning.png",
          });
          return;
        }
      }
    });*/
  },

  showCouponPicker: function () {
    var page = this;
    if (page.data.couponList && page.data.couponList.length > 0) {
      page.setData({
        show_coupon_picker: true,
      });
    }
  },

  //选择优惠券
  pickCoupon: function (e) {
    var page = this;
    var index = e.currentTarget.dataset.index;
    if (index == '-1' || index == -1) {
      page.setData({
        picker_coupon: false,
        show_coupon_picker: false,
      });
    } else if (page.data.couponList[index].subStatus == 1 || page.data.couponList[index].subStatus==2){
        wx.showToast({
          title: "该优惠券不可用",
        })
    }else
    {
      page.setData({
        picker_coupon: page.data.couponList[index],
        show_coupon_picker: false,
        new_total_price: parseFloat((page.data.actualPrice - page.data.couponList[index].parPrice).toFixed(2)),
      });
    }
  },

  showShop: function (e) {
    var page = this;
    if (page.data.shop_list && page.data.shop_list.length > 1) {
      page.setData({
        show_shop: true,
      });
    }
  },
  pickShop: function (e) {
    var page = this;
    var index = e.currentTarget.dataset.index;
    if (index == '-1' || index == -1) {
      page.setData({
        shop: false,
        show_shop: false,
      });
    } else {
      page.setData({
        shop: page.data.shop_list[index],
        show_shop: false,
      });
    }
  }

});